package demo;

import static com.xls.commonlibrary.constant.Const.GAME_GOTO_JIFEN;
import static com.xls.commonlibrary.constant.Const.GAME_SHOW_AD;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.bean.UserGameInfo;
import com.xls.commonlibrary.http.biz.UserUtil;
import com.xls.commonlibrary.util.LoginUtil;
import com.xls.commonlibrary.util.SysDataUtil;
import com.xls.commonlibrary.util.TokenUtil;
import com.xls.commonlibrary.util.dislogx.DialogXUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



@SuppressLint("JavascriptInterface")
public class JSBridge {
    public static Handler m_Handler = new Handler(Looper.getMainLooper());
    // public static Activity mMainActivity = null;
    public static AppCompatActivity mMainActivity = null;
    public static WebView webView=null;

    @android.webkit.JavascriptInterface
    public static String getHost() throws JSONException {
        JSONObject json = new JSONObject();

        json.put("host", BuildConfig.BASE_COM_URL_HTTP);
        json.put("token", TokenUtil.getInstance().getToken());
        json.put("pkgName", SysDataUtil.getInstance().getPkName());
        json.put("appId", BuildConfig.APPID);

        String result = json.toString();
        Logger.d("============getHost=============%s", result);

        return result;

    }

    /**
     *  JS获取游戏的用户信息 关卡等信息
      */
    @android.webkit.JavascriptInterface
    public static String getUserInfo() throws JSONException {
        UserGameInfo info = LoginUtil.getInstance().getUser();
        if (info == null) {
            return "login failed";
        }

        JSONObject json = new JSONObject();

        json.put("name", info.getName());
        json.put("headimg", info.getHeadimg());
        json.put("openid", info.getOpenid());
        json.put("redbag", info.getRedbag());
        json.put("money", info.getMoney());
        json.put("level", info.getLevel());// 关卡数

        String result = json.toString();

        return result;

    }

    /**
     * 开始走激励视频流程的弹窗，关闭响应，弹出半屏
     * @throws JSONException
     */
    @android.webkit.JavascriptInterface
    public static void onOpenRewardDialogClose() throws JSONException {
        Logger.d("============onOpenRewardDialogClose=============");

    }

    /**
     * 开始走激励视频流程的弹窗，开始显示，需要开始半屏和激励的前置调取
     * @throws JSONException
     */
    @android.webkit.JavascriptInterface
    public static void onOpenRewardDialogShow() throws JSONException {
        Logger.d("============onOpenRewardDialogShow=============");

    }

    // JS通知游戏 看广告
    @android.webkit.JavascriptInterface
    public static void showReward() throws JSONException {
        // todo 调gmreward
//        Toaster.show("看广告");
        Logger.d("============看广告=============");
        DialogXUtil.showLoading();

        m_Handler.post(
                new Runnable() {
                    public void run() {
                        EventBus.getDefault().post(new MessageEvent(GAME_SHOW_AD, ""));
                    }
                });

    }

    // JS通知游戏 我的页面
    @android.webkit.JavascriptInterface
    public static void showMine() throws JSONException {
        // todo 调gmreward
//        Toaster.show("我得页面");
        Logger.d("============我得页面=============");
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        EventBus.getDefault().post(new MessageEvent(GAME_GOTO_JIFEN, ""));
                    }
                });

    }

    // 两步，才能更新JS的数据
    //游戏通知JS 更新红包数据    广告close后
    // 先调  ConchJNI.RunJS("AndroidSDK && AndroidSDK.closeAppVideoViewADCallBack(0,'"+message+"');");
    // code==0是成功，msg传空过来就行。code!=0是失败，msg传错误描述过来就行。
    // 1
    // 缓存用户数据成功后再调用 todo
    @android.webkit.JavascriptInterface
    public static void closeAppVideoViewADCallBack(boolean isSucces, String message) {
        // ad要游戏更新数据
        Logger.d("=JSBridge=====notifyUpdateMoney==========:@%b", isSucces);
        webView.evaluateJavascript("AndroidSDK.closeAppVideoViewADCallBack(0,'" + message + "')",null);
//        ConchJNI.RunJS("AndroidSDK && AndroidSDK.closeAppVideoViewADCallBack(0,'" + message + "');");
    }
//    @android.webkit.JavascriptInterface
    public static void updateData() {
        // 其他时候要游戏更新数据
        Logger.d("=JSBridge=====updateData==========");
        webView.evaluateJavascript("AndroidSDK.updateData()",null);
//        ConchJNI.RunJS("AndroidSDK && AndroidSDK.updateData();");
    }


//    // 通知游戏，游戏再调  updateMoney  获取最新红包数据
//    // 2
//    // todo  需要【个人信息接口】增加分数，返回给游戏
    @android.webkit.JavascriptInterface
    public static String updateMoney() throws JSONException {
//        Toaster.show("updateMoney");


        UserGameInfo info = LoginUtil.getInstance().getUser();


        Logger.d("==JSBridge===updateMoney======", info.toString());


        if (info == null) {
            return "login failed";
        }

        JSONObject json = new JSONObject();
        json.put("redbag", info.getRedbag());
        json.put("money", info.getMoney());

        String result = json.toString();
        return result;


    }
//
//
//    // JS通知游戏 过关更新游戏数据
//    // todo 需要新增接口，update个人信息的 关卡数
    @android.webkit.JavascriptInterface
    public static void updateGameInfo(final String level) {
//        Toaster.show("updateGameInfo：  " + level);

        // 异步任务必须用handler
        m_Handler.post(
                new Runnable() {
                    public void run() {

                        UserUtil.getInstance().updateUserGameAccount(mMainActivity, level, tag -> {
                            if (tag) {
                                notifyUpdateMoney(true, "ok");
                            }
                        });
                    }

                });
    }

    // 两步，才能更新JS的数据
    //游戏通知JS 更新红包数据    广告close后
    // 先调  ConchJNI.RunJS("AndroidSDK && AndroidSDK.closeAppVideoViewADCallBack(0,'"+message+"');");
    // code==0是成功，msg传空过来就行。code!=0是失败，msg传错误描述过来就行。
    // 1
    // 缓存用户数据成功后再调用 todo
    @android.webkit.JavascriptInterface
    public static void notifyUpdateMoney(boolean isSucces, String message) {
        Logger.d("=JSBridge=====notifyUpdateMoney==========:@%b", isSucces);
        if (isSucces) {
            webView.evaluateJavascript("AndroidSDK.closeAppVideoViewADCallBack(0,'" + message + "')",null);
        } else {
            webView.evaluateJavascript("AndroidSDK.closeAppVideoViewADCallBack(999,'" + message +"')",null);
        }
    }

    @android.webkit.JavascriptInterface
    public static void hideSplash() {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        GameDdxActivity.mSplashDialog.dismissSplash();
                    }
                });
    }
    @android.webkit.JavascriptInterface
    public static void setFontColor(final String color) {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        GameDdxActivity.mSplashDialog.setFontColor(Color.parseColor(color));
                    }
                });
    }

    @android.webkit.JavascriptInterface
    public static void setTips(final JSONArray tips) {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        try {
                            String[] tipsArray = new String[tips.length()];
                            for (int i = 0; i < tips.length(); i++) {
                                tipsArray[i] = tips.getString(i);
                            }
                            GameDdxActivity.mSplashDialog.setTips(tipsArray);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @android.webkit.JavascriptInterface
    public static void bgColor(final String color) {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        GameDdxActivity.mSplashDialog.setBackgroundColor(Color.parseColor(color));
                    }
                });
    }

    @android.webkit.JavascriptInterface
    public static void loading(final double percent) {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        GameDdxActivity.mSplashDialog.setPercent((int) percent);
                    }
                });
    }

    @android.webkit.JavascriptInterface
    public static void showTextInfo(final boolean show) {
        m_Handler.post(
                new Runnable() {
                    public void run() {
                        GameDdxActivity.mSplashDialog.showTextInfo(show);
                    }
                });
    }

    public static void closeMusic() {
        webView.evaluateJavascript("AndroidSDK.closeMusic()",null);
    }


    public static void openMusic() {
        webView.evaluateJavascript("AndroidSDK.openMusic()",null);
    }
}
